package aad.storyboard.controller;

import aad.storyboard.model.Scene;
import aad.storyboard.model.Story;
import android.app.Activity;
import android.util.Log;

public class ControllerManager {
	private ControllerManager(){
		
	}
	private static ControllerManager instance = new ControllerManager();
	private FrameRateController frcPointer;
	private SceneController scPointer;
	private GUIComposer guic;
	private StoryTimer timer;
	private AudioPlayer audioPlayer;
	private Story story;
	private DBAdapter adapter;
	private Activity act;
	
	
	public static ControllerManager getInstance(){
		return instance;
	}
	
	/**
	 * Convenience method for setting up all the controllers, is a facade to the user, such that he/she must not perform all this mechanic instanciations and setups.
	 */
	public void setupControllers(Story s, Activity a, int mainLayout){
		story = s;
		act = a;
		guic = GUIComposer.getInstance();
		guic.setupGUI(s, a, mainLayout);
		frcPointer = FrameRateController.getInstance(guic.getMainView());
		scPointer = SceneController.getInstance(s, frcPointer);
		timer=StoryTimer.getInstance();	
		Story.setTimer();
		timer.addObserver(scPointer);
	    FrameRateController frc = FrameRateController.getInstance(guic.getMainView());
	    scPointer = SceneController.getInstance(s, frc);
		audioPlayer = AudioPlayer.getInstance();
	    audioPlayer.setContext(a);
	    audioPlayer.setfileId(s.getAudioFile());
	    story.getSettings().setActivity(a);
	    AudioPlayer.getInstance().addObserver(timer);
	    adapter = new DBAdapter(a);
	    adapter.open();
	}
	
	//getters and setters for the controllers
	public GUIComposer getGuiComposer() {
		return guic;
	}

	public FrameRateController getFRC(){
		return this.frcPointer;
	}
	
	public SceneController getSC(){
		return this.scPointer;
	}
	
	public DBAdapter getAdapter(){
		return adapter;
	}
	
	
	/**
	 * Starts the story from the beginning
	 */
	public void startStory(){
		audioPlayer.setfileId(story.getAudioFile());
		audioPlayer.playAudio();
	    timer.addObserver(guic.getScriptView());
	    new Thread(this.frcPointer).start();
	    timer.run();
	}
	/**
	 * Starts the story from a certain scene
	 */
	public void startStory(Scene scene){
		Log.e("TAG", "FileID:"+scene.getId()+scene.getStartTime());
		Story.getInstance().restartStoryComponents();
		Story.getInstance().startFromScene(scene);
		audioPlayer.setfileId(story.getAudioFile());
	    audioPlayer.seekToPosition(scene.getStartTime());
	    timer.addObserver(guic.getScriptView());
	    new Thread(this.frcPointer).start();
		audioPlayer.playAudio();
	    timer.run();
	}

	public Activity getActivity() {
		return this.act;
		
	}

}
